package client.util;

import client.functionalities.LocalFunctionality;
import client.functionalities.RemoteFunctionality;
import client.screen.AlertScreen;

public class AlertThread extends Thread {
	private LocalFunctionality lFunctionality = null;
	private RemoteFunctionality remoteFunctionality = null;
	private AlertScreen alertScreen;
	private String message;
	private int mode;
	
	public static final int MODE_FUNCTIONALITY = 0;
	public static final int MODE_LOCALFUNCTIONALITY = 1;	
	
	public AlertThread(AlertScreen alertScreen, RemoteFunctionality remoteFunctionality, String message) {
		super(message);
		
		this.message = message;
		this.alertScreen = alertScreen;
		this.remoteFunctionality = remoteFunctionality;
		this.mode = AlertThread.MODE_FUNCTIONALITY;
	}
	
	public AlertThread(AlertScreen alertScreen, LocalFunctionality lf, String message) {
		super(message);
		
		this.message = message;
		this.alertScreen = alertScreen;
		this.lFunctionality = lf;
		this.mode = AlertThread.MODE_LOCALFUNCTIONALITY;
	}
	
	public void run() {
		switch (this.mode) {
		case AlertThread.MODE_FUNCTIONALITY:
		{
			this.remoteFunctionality.start();
			
			// Ajusta a mensagem
			setAlert(message);

			// Esta thread acaba quando a ref acabar (o comando mudar de estado,
			// por ex, a thread da lista de amigos acabar ou a thread de enviar
			// scrap), podendo o usuario cancelar a operacao com o comando exit.
			
			// TODO Novo sistema de timer
			long time = System.currentTimeMillis();
			while (this.remoteFunctionality.isRunning()) {
				if (System.currentTimeMillis() > (time + 15000)) {
					// Fecha forçadamente após 15 segundos de timeout
					this.remoteFunctionality.stop();
					break;
				}
			}
		}
		case AlertThread.MODE_LOCALFUNCTIONALITY:
		{
			this.lFunctionality.start();
			
			// Ajusta a mensagem
			setAlert(message);

			// Esta thread acaba quando a ref acabar (o comando mudar de estado,
			// por ex, a thread da lista de amigos acabar ou a thread de enviar
			// scrap), podendo o usuario cancelar a operacao com o comando exit.
			
			// TODO Novo sistema de timer
			long time = System.currentTimeMillis();
			while (this.lFunctionality.isRunning()) {
				if (System.currentTimeMillis() > (time + 15000)) {
					// Fecha forçadamente após 15 segundos de timeout
					this.lFunctionality.stop();
					break;
				}
			}
		}
		}
	}
		
	private void setAlert(String message) {
		this.alertScreen.setString(message);
	}
	
}
